import React, { useState } from 'react';
import { Box, GridCarousel, GridItem, Icon, MainButton, Text } from '@nova-hf/ui';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import { formatDate } from 'beta/utils/helpers';
import { uniqBy } from 'lodash';
import {
  AppointmentInfoInput,
  FiberProvider,
  useFiberAppointmentSlotsQuery,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

type FiberInstallationProps = {
  color: MainColorType;
  provider: FiberProvider;
  propertyId: string;
  userNationalId: string;
  onComplete: (slot: AppointmentInfoInput | undefined) => void;
};

export const FiberInstallation = ({
  color,
  provider,
  propertyId,
  userNationalId,
  onComplete,
}: FiberInstallationProps) => {
  const [selectedSlot, setSelectedSlot] = useState<AppointmentInfoInput | undefined>();
  const { t } = useTranslation('flutningur');
  const { data, loading, error } = useFiberAppointmentSlotsQuery({
    variables: {
      input: {
        propertyId,
        nationalId: userNationalId,
        provider,
      },
    },
    skip: provider === FiberProvider.Tengir,
  });

  const onSelectSlot = (slot?: AppointmentInfoInput) => {
    setSelectedSlot(slot);
    onComplete(slot);
  };

  return (
    <>
      {error && <Text>{t('flutningur.new.installation.error')}</Text>}
      {loading && <Text>{t('flutningur.new.installation.loading')}</Text>}
      {!error && !loading && provider !== FiberProvider.Tengir ? (
        <GridCarousel
          color={color}
          numberOnSlide={18}
          gridTemplate={{ sm: 4, md: 6, lg: 6, xl: 12 }}
          gridGap={{ sm: 2, lg: 3 }}
          backButtonHiddenTitle=""
          nextButtonHiddenTitle=""
        >
          <GridItem gridColumn={{ sm: 'span2', xl: 'span3' }}>
            <Box
              renderAs="button"
              height="100%"
              width="100%"
              display="flex"
              justifyContent="space-around"
              alignItems="center"
              paddingX={3}
              paddingY={3}
              borderColor={{
                hover: color,
                focusVisible: color,
                sm: !selectedSlot?.slotId ? color : 'grey200',
              }}
              onClick={() => onSelectSlot(undefined)}
              borderStyle="solid"
              borderWidth="2px"
              dottedShadow={{ sm: 'none', md: 'small' }}
              backgroundColor="white"
            >
              <Icon icon="phoneHeart" color={color} />
              <Text variant="pLargeBold">{'Fá símtal'}</Text>
            </Box>
          </GridItem>

          {uniqBy(data?.fiberAppointmentSlots?.availableSlots, 'startTime')?.map((slot, i) => {
            return (
              <GridItem key={i} gridColumn={{ sm: 'span2', xl: 'span3' }}>
                <Box
                  renderAs="button"
                  width="100%"
                  display="flex"
                  justifyContent="space-around"
                  alignItems="center"
                  paddingX={3}
                  paddingY={4}
                  borderColor={{
                    hover: color,
                    focusVisible: color,
                    sm:
                      selectedSlot?.startTime === slot.startTime && selectedSlot?.slotId
                        ? color
                        : 'grey200',
                  }}
                  borderStyle="solid"
                  borderWidth="2px"
                  onClick={() =>
                    onSelectSlot({
                      appointmentId: data?.fiberAppointmentSlots?.appointmentId,
                      slotId: slot.id ?? '',
                      startTime: slot.startTime,
                    })
                  }
                  dottedShadow={{ sm: 'none', md: 'small' }}
                  backgroundColor="white"
                >
                  <Icon icon="calendar" color={color} />
                  <Text variant="pLargeBold">{formatDate(slot.startTime as Date, 'dd.MM.yy')}</Text>
                  <Text variant="pLargeBold">{formatDate(slot.startTime as Date, 'HH:mm')}</Text>
                </Box>
              </GridItem>
            );
          })}
        </GridCarousel>
      ) : (
        <Box display="flex" flexDirection="column">
          <Text variant="h6" marginBottom={2}>
            Tengir hefur samband
          </Text>
          <MainButton
            text={'Áfram'}
            onClick={() =>
              onSelectSlot({
                appointmentId: '',
                slotId: '',
                startTime: new Date(),
              })
            }
          />
        </Box>
      )}
    </>
  );
};
